package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.YiJi_Class;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Main_BianJi_ServiceActivity extends Activity implements
        OnClickListener {
    private ImageView bianji_service_back;
    private EditText editText_bianji_service_title,
            editText_bianji_service_details;
    private Button bianji_fuwu_yiji, button_erji_bianji_fuwu_fenlei,
            button_sanjibianji__fenlei, button_tijiao;
    private CustomProgressDialog mCustomProgressDialog;
    //    private SharedPreferences sp;
//    private Editor ed;
    private int yiji_id, erji_id, sanji_id;
    private PopupWindow show_popupWindow;
    private ListView show_listview;
    private LinearLayout layout, bianji_fuwu;
    private ArrayList<YiJi_Class> list = new ArrayList<YiJi_Class>();
    private boolean yiji_flag = false, erji_flag = true, sanji_flag = true;
    private MyAdapter mMyAdapter;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    show_listview.setAdapter(mMyAdapter);
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__bian_ji__service);
        // XJApplication.getInstance().addActivity(this);
        bianji_service_back = (ImageView) findViewById(R.id.bianji_service_back);
        editText_bianji_service_title = (EditText) findViewById(R.id.editText_bianji_service_title);
        bianji_fuwu_yiji = (Button) findViewById(R.id.bianji_fuwu_yiji);
        button_erji_bianji_fuwu_fenlei = (Button) findViewById(R.id.button_erji_bianji_fuwu_fenlei);
        button_sanjibianji__fenlei = (Button) findViewById(R.id.button_sanjibianji__fenlei);
        button_tijiao = (Button) findViewById(R.id.button_tijiao);
        mMyAdapter = new MyAdapter();
        bianji_fuwu = (LinearLayout) findViewById(R.id.bianji_fuwu);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        editText_bianji_service_details = (EditText) findViewById(R.id.editText_bianji_service_details);
        mCustomProgressDialog = CustomProgressDialog.createDialog(this);
        mCustomProgressDialog.setCanceledOnTouchOutside(false);
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_service_information();
            }
        });
        bianji_service_back.setOnClickListener(this);
        button_tijiao.setOnClickListener(this);
        bianji_fuwu_yiji.setOnClickListener(this);
        button_erji_bianji_fuwu_fenlei.setOnClickListener(this);
        button_sanjibianji__fenlei.setOnClickListener(this);
        bianji_fuwu.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bianji_service_back) {
            this.finish();
        } else if (v.getId() == R.id.button_tijiao) {
            if (editText_bianji_service_title.getText().toString().length() > 0) {
                if (erji_flag) {
                    if (sanji_flag) {
                        if (editText_bianji_service_details.getText()
                                .toString().length() > 0) {
                            mCustomProgressDialog = CustomProgressDialog.createDialog(this);
                            mCustomProgressDialog.setCanceledOnTouchOutside(false);
                            mCustomProgressDialog.show();
                            tijiao();
                        } else {
                            Toast.makeText(Main_BianJi_ServiceActivity.this, "请填写服务内容", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(Main_BianJi_ServiceActivity.this, "请先选择三级分类", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(Main_BianJi_ServiceActivity.this, "请先选择二级分类", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(Main_BianJi_ServiceActivity.this, "请输入服务名称", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.bianji_fuwu_yiji) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.bianji_fuwu), Gravity.BOTTOM, 0, 0);
            mCustomProgressDialog = CustomProgressDialog.createDialog(this);
            mCustomProgressDialog.setCanceledOnTouchOutside(false);
            mCustomProgressDialog.show();
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    yiji_fenlei();
                }
            });

            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    bianji_fuwu_yiji.setText(list.get(arg2).getName());
                    bianji_fuwu_yiji.setTextColor(getResources().getColor(
                            R.color.black3F));
                    yiji_id = list.get(arg2).getId();

                    button_erji_bianji_fuwu_fenlei.setText("请选择二级分类");
                    button_erji_bianji_fuwu_fenlei.setTextColor(getResources()
                            .getColor(R.color.gray98));
                    button_sanjibianji__fenlei.setText("请选择三级分类");
                    button_sanjibianji__fenlei.setTextColor(getResources()
                            .getColor(R.color.gray98));
                    erji_flag = false;
                    sanji_flag = false;
                    show_popupWindow.dismiss();
                    show_popupWindow = null;

                    yiji_flag = true;
                }
            });

        } else if (v.getId() == R.id.button_erji_bianji_fuwu_fenlei) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.bianji_fuwu),
                    Gravity.BOTTOM, 0, 0);
            mCustomProgressDialog = CustomProgressDialog.createDialog(this);
            mCustomProgressDialog.setCanceledOnTouchOutside(false);
            mCustomProgressDialog.show();
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    erji_fenlei();
                }
            });

            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    erji_id = list.get(arg2).getId();
                    button_erji_bianji_fuwu_fenlei.setText(list.get(arg2)
                            .getName());
                    button_erji_bianji_fuwu_fenlei.setTextColor(getResources()
                            .getColor(R.color.black3F));
                    button_sanjibianji__fenlei.setText("请选择三级分类");
                    button_sanjibianji__fenlei.setTextColor(getResources()
                            .getColor(R.color.gray98));
                    erji_flag = true;
                    sanji_flag = false;
                    show_popupWindow.dismiss();
                    show_popupWindow = null;

                }
            });

        } else if (v.getId() == R.id.button_sanjibianji__fenlei) {
            if (erji_flag) {
                Photo_show();
                show_popupWindow.showAtLocation(findViewById(R.id.bianji_fuwu),
                        Gravity.BOTTOM, 0, 0);
                mCustomProgressDialog = CustomProgressDialog.createDialog(this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                sanji_fenlei();

                show_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        sanji_id = list.get(arg2).getId();
                        button_sanjibianji__fenlei.setText(list.get(arg2)
                                .getName());
                        button_sanjibianji__fenlei.setTextColor(getResources()
                                .getColor(R.color.black3F));
                        sanji_flag = true;
                        show_popupWindow.dismiss();
                        show_popupWindow = null;
                    }
                });
            } else {
                Toast.makeText(Main_BianJi_ServiceActivity.this, "请先选择二级分类", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.bianji_fuwu) {
            if (show_popupWindow != null) {
                show_popupWindow.dismiss();
                show_popupWindow = null;
            }
        }
    }

    public void get_service_information() {

        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("caseId", getIntent().getIntExtra("caseId", 0));
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.get_service, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        JSONObject obj = array.getJSONObject(0);
                        editText_bianji_service_title.setText(obj
                                .getString("title"));
                        editText_bianji_service_details.setText(obj
                                .getString("details"));
                        bianji_fuwu_yiji.setText(obj
                                .getString("parent_name"));
                        bianji_fuwu_yiji.setTextColor(getResources()
                                .getColor(R.color.black3F));
                        yiji_id = obj.getInt("parent");
                        sanji_id = obj.getInt("categorytwo");
                        erji_id = obj.getInt("category");

                        button_erji_bianji_fuwu_fenlei.setText(obj
                                .getString("cat_name"));
                        if (obj.getInt("categorytwo") == 0) {
                            button_sanjibianji__fenlei.setText("其他");
                        } else {
                            button_sanjibianji__fenlei.setText(obj
                                    .getString("cattwo_name"));
                        }
                        button_sanjibianji__fenlei
                                .setTextColor(getResources().getColor(
                                        R.color.black3F));

                        button_erji_bianji_fuwu_fenlei
                                .setTextColor(getResources().getColor(
                                        R.color.black3F));

                        if (mCustomProgressDialog != null) {
                            mCustomProgressDialog.dismiss();
                            mCustomProgressDialog = null;
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }

            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();

    }

    public void yiji_fenlei() {

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("cid", 0);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.geren_fuwu_fenlei, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        JSONArray array1 = array.getJSONArray(0);
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject object = array1.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(object.getInt("id"));
                            mYiJi_Class.setName(object
                                    .getString("name"));
                            list.add(mYiJi_Class);

                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_BianJi_ServiceActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();

    }

    public void erji_fenlei() {

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("cid", yiji_id);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.geren_fuwu_fenlei, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        JSONArray array1 = array.getJSONArray(0);
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject object = array1.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(object.getInt("id"));
                            mYiJi_Class.setName(object
                                    .getString("name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_BianJi_ServiceActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();

    }

    public void sanji_fenlei() {

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));

        map.put("cid", erji_id);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.geren_fuwu_fenlei, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        JSONArray array1 = array.getJSONArray(0);
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject object = array1.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(object.getInt("id"));
                            mYiJi_Class.setName(object
                                    .getString("name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_BianJi_ServiceActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();

    }

    /**
     * 重新编辑提交
     */
    public void tijiao() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("caseId", getIntent().getIntExtra("caseId", 0));
        map.put("title", editText_bianji_service_title.getText().toString());
        map.put("details", editText_bianji_service_details.getText().toString());
        map.put("parent", yiji_id);
        map.put("category", erji_id);
        map.put("categorytwo", sanji_id);

        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.tijiao_service, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        Toast.makeText(
                                Main_BianJi_ServiceActivity.this,
                                response.getString("msg"), Toast.LENGTH_SHORT).show();
                        Main_BianJi_ServiceActivity.this.finish();
                    } else {
                        Toast.makeText(Main_BianJi_ServiceActivity.this,
                                response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }

                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();

    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_BianJi_ServiceActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout
                .findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);
        if (show_popupWindow == null) {
            show_popupWindow = new PopupWindow(layout,
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
            show_popupWindow.setHeight(700);
            show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
            show_popupWindow.update();
            show_popupWindow.setOutsideTouchable(false);
            show_popupWindow.setFocusable(false);
            show_popupWindow.setContentView(layout);
        }
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_BianJi_ServiceActivity.this,
                        R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView
                        .findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(list.get(position).getName());
            return convertView;
        }
    }

    class Holder {
        TextView place_text;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
